from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.utils.html import format_html
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.db.models import Count, Q
from django.http import HttpResponseRedirect
from django.contrib.admin import SimpleListFilter
from django.utils.translation import gettext_lazy as _
import datetime

from .models import (
    Organization, Location, Department, UserProfile,
    AssetCategory, Supplier, Contract, Asset, AssetLog,
    Warehouse, Consumable, InventoryLog, AssetLedger,
    AssetBorrow
)

# 导入其他模型
try:
    from .models_transfer import AssetTransfer, AssetTransferItem
    from .models_workflow import WorkflowTemplate, WorkflowInstance
    from .models_system import SystemLog, SystemParameter, DataBackup
    from .models_ai import (
        AssetRecommendation, AssetAnomalyDetection, 
        PredictiveMaintenanceModel, SmartReport
    )
    from .models_software import Software, SoftwareLicense, SoftwareInstallation
    from .models_label import LabelTemplate, LabelPrintHistory
except ImportError:
    pass


# ================================
# 自定义过滤器
# ================================

class AssetStatusFilter(SimpleListFilter):
    """资产状态过滤器"""
    title = _('资产状态')
    parameter_name = 'status'

    def lookups(self, request, model_admin):
        return (
            ('active', _('使用中')),
            ('idle', _('闲置')),
            ('maintenance', _('维修中')),
            ('scrapped', _('已报废')),
        )

    def queryset(self, request, queryset):
        if self.value() == 'active':
            return queryset.filter(status='active')
        if self.value() == 'idle':
            return queryset.filter(status='idle')
        if self.value() == 'maintenance':
            return queryset.filter(status='maintenance')
        if self.value() == 'scrapped':
            return queryset.filter(status='scrapped')


class DateRangeFilter(SimpleListFilter):
    """日期范围过滤器"""
    title = _('创建时间')
    parameter_name = 'date_range'

    def lookups(self, request, model_admin):
        return (
            ('today', _('今天')),
            ('week', _('本周')),
            ('month', _('本月')),
            ('year', _('今年')),
        )

    def queryset(self, request, queryset):
        today = datetime.date.today()
        if self.value() == 'today':
            return queryset.filter(created_at__date=today)
        if self.value() == 'week':
            start_week = today - datetime.timedelta(days=today.weekday())
            return queryset.filter(created_at__date__gte=start_week)
        if self.value() == 'month':
            return queryset.filter(created_at__year=today.year, created_at__month=today.month)
        if self.value() == 'year':
            return queryset.filter(created_at__year=today.year)


# ================================
# 内联编辑器
# ================================

class AssetLogInline(admin.TabularInline):
    """资产日志内联编辑"""
    model = AssetLog
    extra = 0
    readonly_fields = ['created_at']
    fields = ['action', 'description', 'operator', 'created_at']
    ordering = ['-created_at']


class AssetTransferItemInline(admin.TabularInline):
    """资产调拨项目内联编辑"""
    try:
        model = AssetTransferItem
        extra = 1
        fields = ['asset', 'from_department', 'to_department', 'from_location', 'to_location', 'notes']
    except NameError:
        pass


class UserProfileInline(admin.StackedInline):
    """用户档案内联编辑"""
    model = UserProfile
    can_delete = False
    verbose_name_plural = '用户档案'
    fields = ['employee_id', 'department', 'phone', 'allowed_organizations', 'allowed_ledgers']


# ================================
# 管理类定义
# ================================

@admin.register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
    list_display = ['name', 'code', 'asset_count', 'department_count', 'created_at']
    search_fields = ['name', 'code', 'description']
    list_filter = [DateRangeFilter]
    ordering = ['name']
    readonly_fields = ['created_at', 'updated_at']
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'code', 'description')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def asset_count(self, obj):
        count = obj.department_set.aggregate(
            asset_count=Count('asset')
        )['asset_count'] or 0
        return format_html(
            '<span style="color: #007cba; font-weight: bold;">{}</span>',
            count
        )
    asset_count.short_description = '资产数量'
    
    def department_count(self, obj):
        count = obj.department_set.count()
        return format_html(
            '<span style="color: #28a745; font-weight: bold;">{}</span>',
            count
        )
    department_count.short_description = '部门数量'


@admin.register(Location)
class LocationAdmin(admin.ModelAdmin):
    list_display = ['name', 'address', 'asset_count', 'warehouse_count', 'created_at']
    search_fields = ['name', 'address']
    list_filter = [DateRangeFilter]
    ordering = ['name']
    readonly_fields = ['created_at', 'updated_at']
    
    def asset_count(self, obj):
        count = Asset.objects.filter(
            Q(department__location=obj) | Q(location=obj)
        ).count()
        return format_html(
            '<span style="color: #007cba; font-weight: bold;">{}</span>',
            count
        )
    asset_count.short_description = '资产数量'
    
    def warehouse_count(self, obj):
        count = obj.warehouse_set.count()
        return format_html(
            '<span style="color: #6f42c1; font-weight: bold;">{}</span>',
            count
        )
    warehouse_count.short_description = '仓库数量'


@admin.register(Department)
class DepartmentAdmin(admin.ModelAdmin):
    list_display = ['name', 'code', 'organization', 'location', 'asset_count', 'user_count', 'created_at']
    list_filter = ['organization', 'location', DateRangeFilter]
    search_fields = ['name', 'code']
    ordering = ['organization', 'name']
    readonly_fields = ['created_at', 'updated_at']
    autocomplete_fields = ['organization', 'location', 'parent']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'code', 'organization', 'location', 'parent')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def asset_count(self, obj):
        count = obj.asset_set.count()
        return format_html(
            '<span style="color: #007cba; font-weight: bold;">{}</span>',
            count
        )
    asset_count.short_description = '资产数量'
    
    def user_count(self, obj):
        count = obj.userprofile_set.count()
        return format_html(
            '<span style="color: #28a745; font-weight: bold;">{}</span>',
            count
        )
    user_count.short_description = '用户数量'


class CustomUserAdmin(UserAdmin):
    """自定义用户管理"""
    inlines = [UserProfileInline]
    list_display = ['username', 'email', 'first_name', 'last_name', 'department_info', 'is_active', 'date_joined']
    list_filter = ['is_active', 'is_staff', 'is_superuser', DateRangeFilter]
    
    def department_info(self, obj):
        try:
            profile = obj.userprofile
            if profile.department:
                return format_html(
                    '<span style="color: #007cba;">{}</span>',
                    profile.department.name
                )
            return '-'
        except UserProfile.DoesNotExist:
            return '-'
    department_info.short_description = '所属部门'


@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ['user', 'employee_id', 'department', 'phone', 'organization_access', 'created_at']
    list_filter = ['department', 'allowed_organizations']
    search_fields = ['user__username', 'user__first_name', 'user__last_name', 'employee_id', 'phone']
    autocomplete_fields = ['user', 'department']
    filter_horizontal = ['allowed_organizations', 'allowed_ledgers']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('user', 'employee_id', 'department', 'phone')
        }),
        ('权限设置', {
            'fields': ('allowed_organizations', 'allowed_ledgers'),
            'classes': ('wide',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def organization_access(self, obj):
        count = obj.allowed_organizations.count()
        if count > 0:
            return format_html(
                '<span style="color: #28a745; font-weight: bold;">{} 个组织</span>',
                count
            )
        return '无限制'
    organization_access.short_description = '组织访问权限'


@admin.register(AssetCategory)
class AssetCategoryAdmin(admin.ModelAdmin):
    list_display = ['name', 'code', 'asset_count', 'description_truncated', 'created_at']
    search_fields = ['name', 'code', 'description']
    list_filter = [DateRangeFilter]
    ordering = ['name']
    readonly_fields = ['created_at', 'updated_at']
    
    def asset_count(self, obj):
        count = obj.asset_set.count()
        return format_html(
            '<span style="color: #007cba; font-weight: bold;">{}</span>',
            count
        )
    asset_count.short_description = '资产数量'
    
    def description_truncated(self, obj):
        if obj.description:
            return obj.description[:50] + '...' if len(obj.description) > 50 else obj.description
        return '-'
    description_truncated.short_description = '描述'


@admin.register(Supplier)
class SupplierAdmin(admin.ModelAdmin):
    list_display = ['name', 'contact_person', 'phone', 'email', 'contract_count', 'cooperation_status', 'created_at']
    search_fields = ['name', 'contact_person', 'phone', 'email']
    list_filter = [DateRangeFilter]
    ordering = ['name']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'contact_person', 'phone', 'email', 'address')
        }),
        ('合作信息', {
            'fields': ('cooperation_count', 'credit_rating', 'blacklist_status', 'blacklist_reason'),
            'classes': ('wide',)
        }) if hasattr(Supplier, 'cooperation_count') else None,
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def contract_count(self, obj):
        count = obj.contract_set.count()
        return format_html(
            '<span style="color: #007cba; font-weight: bold;">{}</span>',
            count
        )
    contract_count.short_description = '合同数量'
    
    def cooperation_status(self, obj):
        if hasattr(obj, 'blacklist_status') and obj.blacklist_status:
            return format_html(
                '<span style="color: #dc3545; font-weight: bold;">黑名单</span>'
            )
        return format_html(
            '<span style="color: #28a745; font-weight: bold;">正常</span>'
        )
    cooperation_status.short_description = '合作状态'


@admin.register(Contract)
class ContractAdmin(admin.ModelAdmin):
    list_display = ['name', 'contract_number', 'supplier', 'status_colored', 'amount_formatted', 'start_date', 'end_date', 'progress']
    list_filter = ['status', 'supplier', DateRangeFilter]
    search_fields = ['name', 'contract_number', 'supplier__name']
    date_hierarchy = 'start_date'
    autocomplete_fields = ['supplier']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'contract_number', 'supplier', 'status')
        }),
        ('合同内容', {
            'fields': ('amount', 'start_date', 'end_date', 'description'),
            'classes': ('wide',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def status_colored(self, obj):
        colors = {
            'draft': '#6c757d',
            'active': '#28a745', 
            'expired': '#dc3545',
            'terminated': '#ffc107'
        }
        color = colors.get(obj.status, '#007cba')
        return format_html(
            '<span style="color: {}; font-weight: bold;">{}</span>',
            color,
            obj.get_status_display()
        )
    status_colored.short_description = '状态'
    
    def amount_formatted(self, obj):
        if hasattr(obj, 'amount') and obj.amount:
            return format_html(
                '<span style="color: #007cba; font-weight: bold;">¥{:,.2f}</span>',
                obj.amount
            )
        return '-'
    amount_formatted.short_description = '合同金额'
    
    def progress(self, obj):
        if obj.start_date and obj.end_date:
            today = datetime.date.today()
            total_days = (obj.end_date - obj.start_date).days
            elapsed_days = (today - obj.start_date).days
            
            if elapsed_days < 0:
                progress_percent = 0
            elif elapsed_days > total_days:
                progress_percent = 100
            else:
                progress_percent = int((elapsed_days / total_days) * 100)
            
            color = '#28a745' if progress_percent < 80 else '#ffc107' if progress_percent < 95 else '#dc3545'
            
            return format_html(
                '<div style="width: 100px; background: #e9ecef; border-radius: 10px; overflow: hidden;">' +
                '<div style="width: {}%; background: {}; height: 20px; line-height: 20px; text-align: center; color: white; font-size: 12px; font-weight: bold;">{}%</div>' +
                '</div>',
                progress_percent,
                color,
                progress_percent
            )
        return '-'
    progress.short_description = '执行进度'


@admin.register(Asset)
class AssetAdmin(admin.ModelAdmin):
    list_display = ['asset_number', 'name', 'category', 'department', 'status_colored', 'purchase_date', 'value_formatted', 'action_links']
    list_filter = [AssetStatusFilter, 'category', 'department', 'ledger', DateRangeFilter]
    search_fields = ['name', 'asset_number', 'serial_number']
    date_hierarchy = 'purchase_date'
    autocomplete_fields = ['category', 'department', 'supplier', 'ledger']
    readonly_fields = ['created_at', 'updated_at', 'qr_code_display']
    inlines = [AssetLogInline]
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'asset_number', 'category', 'serial_number')
        }),
        ('位置和状态', {
            'fields': ('department', 'location', 'status', 'ledger'),
            'classes': ('wide',)
        }),
        ('采购信息', {
            'fields': ('supplier', 'purchase_date', 'purchase_price', 'warranty_end_date')
        }),
        ('媒体文件', {
            'fields': ('image', 'qr_code_display'),
            'classes': ('collapse',)
        }),
        ('详细信息', {
            'fields': ('description', 'specifications'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    actions = ['make_idle', 'make_active', 'export_selected']
    
    def status_colored(self, obj):
        colors = {
            'active': '#28a745',
            'idle': '#6c757d', 
            'maintenance': '#ffc107',
            'scrapped': '#dc3545',
            'borrowed': '#007cba',
            'faulty': '#fd7e14'
        }
        color = colors.get(obj.status, '#007cba')
        return format_html(
            '<span style="color: {}; font-weight: bold;">{}</span>',
            color,
            obj.get_status_display()
        )
    status_colored.short_description = '状态'
    
    def value_formatted(self, obj):
        if obj.purchase_price:
            return format_html(
                '<span style="color: #007cba; font-weight: bold;">¥{:,.2f}</span>',
                obj.purchase_price
            )
        return '-'
    value_formatted.short_description = '采购价格'
    
    def qr_code_display(self, obj):
        if hasattr(obj, 'qr_code') and obj.qr_code:
            return format_html(
                '<img src="{}" width="100" height="100" style="border: 1px solid #ddd; border-radius: 5px;"/>',
                obj.qr_code.url
            )
        return '无二维码'
    qr_code_display.short_description = '二维码'
    
    def action_links(self, obj):
        actions_html = [
            f'<a href="{reverse("admin:assets_asset_change", args=[obj.pk])}" style="color: #007cba; margin-right: 10px;">编辑</a>',
        ]
        
        if hasattr(obj, 'assetborrow_set'):
            actions_html.append(
                f'<a href="/admin/assets/assetborrow/add/?asset={obj.pk}" style="color: #28a745; margin-right: 10px;">借用</a>'
            )
        
        return format_html(''.join(actions_html))
    action_links.short_description = '操作'
    
    def make_idle(self, request, queryset):
        updated = queryset.update(status='idle')
        self.message_user(request, f'成功将 {updated} 个资产设置为闲置状态。')
    make_idle.short_description = '设为闲置'
    
    def make_active(self, request, queryset):
        updated = queryset.update(status='active')
        self.message_user(request, f'成功将 {updated} 个资产设置为使用中状态。')
    make_active.short_description = '设为使用中'
    
    def export_selected(self, request, queryset):
        # 这里可以实现导出功能
        self.message_user(request, f'已选择 {queryset.count()} 个资产进行导出。')
    export_selected.short_description = '导出选中项'


@admin.register(AssetLedger)
class AssetLedgerAdmin(admin.ModelAdmin):
    list_display = ['name', 'code', 'organization', 'active_status', 'asset_count', 'created_at']
    list_filter = ['organization', 'active', DateRangeFilter]
    search_fields = ['name', 'code', 'description']
    autocomplete_fields = ['organization']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'code', 'organization', 'active')
        }),
        ('详细信息', {
            'fields': ('description',),
            'classes': ('wide',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def active_status(self, obj):
        if obj.active:
            return format_html(
                '<span style="color: #28a745; font-weight: bold;">启用</span>'
            )
        return format_html(
            '<span style="color: #dc3545; font-weight: bold;">禁用</span>'
        )
    active_status.short_description = '状态'
    
    def asset_count(self, obj):
        count = obj.asset_set.count()
        return format_html(
            '<span style="color: #007cba; font-weight: bold;">{}</span>',
            count
        )
    asset_count.short_description = '资产数量'


@admin.register(AssetLog)
class AssetLogAdmin(admin.ModelAdmin):
    list_display = ['asset_link', 'action_colored', 'operator', 'description_truncated', 'created_at']
    list_filter = ['action', DateRangeFilter]
    search_fields = ['asset__asset_number', 'asset__name', 'description', 'operator__username']
    date_hierarchy = 'created_at'
    readonly_fields = ['created_at']
    autocomplete_fields = ['asset', 'operator']
    
    def asset_link(self, obj):
        url = reverse('admin:assets_asset_change', args=[obj.asset.pk])
        return format_html(
            '<a href="{}" style="color: #007cba; font-weight: bold;">{}</a>',
            url,
            obj.asset.name
        )
    asset_link.short_description = '资产'
    
    def action_colored(self, obj):
        colors = {
            'create': '#28a745',
            'update': '#007cba',
            'allocate': '#6f42c1',
            'transfer': '#fd7e14',
            'maintenance': '#ffc107',
            'scrap': '#dc3545'
        }
        color = colors.get(obj.action, '#6c757d')
        return format_html(
            '<span style="color: {}; font-weight: bold;">{}</span>',
            color,
            obj.get_action_display()
        )
    action_colored.short_description = '操作类型'
    
    def description_truncated(self, obj):
        if obj.description:
            return obj.description[:50] + '...' if len(obj.description) > 50 else obj.description
        return '-'
    description_truncated.short_description = '描述'


@admin.register(Warehouse)
class WarehouseAdmin(admin.ModelAdmin):
    list_display = ['name', 'location', 'manager', 'consumable_count', 'total_value', 'created_at']
    list_filter = ['location', DateRangeFilter]
    search_fields = ['name', 'description']
    autocomplete_fields = ['location', 'manager']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'location', 'manager')
        }),
        ('详细信息', {
            'fields': ('description',),
            'classes': ('wide',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def consumable_count(self, obj):
        count = obj.consumable_set.count()
        return format_html(
            '<span style="color: #007cba; font-weight: bold;">{}</span>',
            count
        )
    consumable_count.short_description = '耗材种类'
    
    def total_value(self, obj):
        # 这里可以计算仓库总价值，需要根据实际模型调整
        return format_html(
            '<span style="color: #28a745; font-weight: bold;">¥0.00</span>'
        )
    total_value.short_description = '库存总价值'


@admin.register(Consumable)
class ConsumableAdmin(admin.ModelAdmin):
    list_display = ['name', 'code', 'category', 'warehouse', 'quantity_status', 'unit', 'min_quantity', 'created_at']
    list_filter = ['category', 'warehouse', DateRangeFilter]
    search_fields = ['name', 'code', 'description']
    autocomplete_fields = ['warehouse']
    readonly_fields = ['created_at', 'updated_at']
    
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'code', 'category', 'warehouse')
        }),
        ('库存信息', {
            'fields': ('quantity', 'min_quantity', 'unit'),
            'classes': ('wide',)
        }),
        ('详细信息', {
            'fields': ('description', 'specifications'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    
    def quantity_status(self, obj):
        if obj.quantity <= obj.min_quantity:
            return format_html(
                '<span style="color: #dc3545; font-weight: bold;">{} (低库存)</span>',
                obj.quantity
            )
        elif obj.quantity <= obj.min_quantity * 1.5:
            return format_html(
                '<span style="color: #ffc107; font-weight: bold;">{} (预警)</span>',
                obj.quantity
            )
        return format_html(
            '<span style="color: #28a745; font-weight: bold;">{}</span>',
            obj.quantity
        )
    quantity_status.short_description = '库存状态'


@admin.register(InventoryLog)
class InventoryLogAdmin(admin.ModelAdmin):
    list_display = ['transaction_type_colored', 'consumable_link', 'quantity_change', 'operator', 'created_at']
    list_filter = ['transaction_type', DateRangeFilter]
    search_fields = ['consumable__name', 'consumable__code', 'notes']
    date_hierarchy = 'created_at'
    readonly_fields = ['created_at']
    autocomplete_fields = ['consumable', 'operator']
    
    def transaction_type_colored(self, obj):
        colors = {
            'in': '#28a745',
            'out': '#dc3545',
            'transfer': '#007cba',
            'adjust': '#ffc107'
        }
        color = colors.get(obj.transaction_type, '#6c757d')
        return format_html(
            '<span style="color: {}; font-weight: bold;">{}</span>',
            color,
            obj.get_transaction_type_display()
        )
    transaction_type_colored.short_description = '交易类型'
    
    def consumable_link(self, obj):
        url = reverse('admin:assets_consumable_change', args=[obj.consumable.pk])
        return format_html(
            '<a href="{}" style="color: #007cba; font-weight: bold;">{}</a>',
            url,
            obj.consumable.name
        )
    consumable_link.short_description = '耗材'
    
    def quantity_change(self, obj):
        if obj.transaction_type in ['in', 'adjust'] and obj.quantity > 0:
            return format_html(
                '<span style="color: #28a745; font-weight: bold;">+{}</span>',
                obj.quantity
            )
        elif obj.transaction_type in ['out'] or obj.quantity < 0:
            return format_html(
                '<span style="color: #dc3545; font-weight: bold;">{}</span>',
                obj.quantity
            )
        return format_html(
            '<span style="color: #007cba; font-weight: bold;">{}</span>',
            obj.quantity
        )
    quantity_change.short_description = '数量变化'


# 如果有其他模型，继续添加
try:
    @admin.register(AssetBorrow)
    class AssetBorrowAdmin(admin.ModelAdmin):
        list_display = ['asset_link', 'borrower', 'borrowed_at', 'expected_return_date', 'status_colored', 'overdue_days']
        list_filter = ['status', 'borrowed_at', DateRangeFilter]
        search_fields = ['asset__name', 'asset__asset_number', 'borrower__username', 'borrower__first_name']
        date_hierarchy = 'borrowed_at'
        autocomplete_fields = ['asset', 'borrower', 'approver']
        readonly_fields = ['created_at', 'approved_at', 'actual_return_date']
        
        fieldsets = (
            ('借用信息', {
                'fields': ('asset', 'borrower', 'borrowed_at', 'expected_return_date')
            }),
            ('审批信息', {
                'fields': ('status', 'approver', 'approved_at', 'approval_notes'),
                'classes': ('wide',)
            }),
            ('归还信息', {
                'fields': ('actual_return_date', 'return_condition', 'return_notes'),
                'classes': ('collapse',)
            }),
            ('时间信息', {
                'fields': ('created_at',),
                'classes': ('collapse',)
            }),
        )
        
        actions = ['approve_selected', 'reject_selected']
        
        def asset_link(self, obj):
            url = reverse('admin:assets_asset_change', args=[obj.asset.pk])
            return format_html(
                '<a href="{}" style="color: #007cba; font-weight: bold;">{}</a>',
                url,
                obj.asset.name
            )
        asset_link.short_description = '资产'
        
        def status_colored(self, obj):
            colors = {
                'pending': '#ffc107',
                'approved': '#007cba',
                'rejected': '#dc3545',
                'borrowed': '#28a745',
                'returned': '#6c757d',
                'overdue': '#dc3545'
            }
            color = colors.get(obj.status, '#6c757d')
            return format_html(
                '<span style="color: {}; font-weight: bold;">{}</span>',
                color,
                obj.get_status_display()
            )
        status_colored.short_description = '状态'
        
        def overdue_days(self, obj):
            if obj.status == 'borrowed' and obj.expected_return_date:
                today = datetime.date.today()
                if today > obj.expected_return_date:
                    days = (today - obj.expected_return_date).days
                    return format_html(
                        '<span style="color: #dc3545; font-weight: bold;">逾期{}天</span>',
                        days
                    )
                else:
                    days = (obj.expected_return_date - today).days
                    return format_html(
                        '<span style="color: #28a745; font-weight: bold;">剩余{}天</span>',
                        days
                    )
            return '-'
        overdue_days.short_description = '逾期情况'
        
        def approve_selected(self, request, queryset):
            updated = 0
            for borrow in queryset.filter(status='pending'):
                if borrow.approve(request.user):
                    updated += 1
            self.message_user(request, f'成功审批通过 {updated} 个借用申请。')
        approve_selected.short_description = '审批通过选中项'
        
        def reject_selected(self, request, queryset):
            updated = 0
            for borrow in queryset.filter(status='pending'):
                if borrow.reject(request.user):
                    updated += 1
            self.message_user(request, f'成功拒绝 {updated} 个借用申请。')
        reject_selected.short_description = '拒绝选中项'
except:
    pass


# 重新注册User admin
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

# 自定义admin站点信息
admin.site.site_header = '固定资产管理系统5.0'
admin.site.site_title = '资产管理'
admin.site.index_title = '管理控制台'


# ================================
# 其他模型的Admin配置
# ================================

# 调拨模块
try:
    @admin.register(AssetTransfer)
    class AssetTransferAdmin(admin.ModelAdmin):
        list_display = ['transfer_number', 'title', 'applicant', 'status_colored', 'priority_colored', 'asset_count_info', 'created_at']
        list_filter = ['status', 'priority', 'transfer_type', DateRangeFilter]
        search_fields = ['transfer_number', 'title', 'applicant__username', 'reason']
        date_hierarchy = 'created_at'
        autocomplete_fields = ['applicant', 'applicant_department', 'target_department', 'target_location', 'approver', 'executor']
        readonly_fields = ['transfer_number', 'created_at', 'updated_at', 'approved_at', 'started_at', 'completed_at']
        inlines = [AssetTransferItemInline] if 'AssetTransferItemInline' in locals() else []
        
        fieldsets = (
            ('基本信息', {
                'fields': ('transfer_number', 'title', 'transfer_type', 'priority')
            }),
            ('申请信息', {
                'fields': ('applicant', 'applicant_department', 'reason', 'description'),
                'classes': ('wide',)
            }),
            ('目标信息', {
                'fields': ('target_department', 'target_location', 'target_user'),
                'classes': ('wide',)
            }),
            ('审批信息', {
                'fields': ('status', 'approver', 'approved_at', 'approval_notes'),
                'classes': ('collapse',)
            }),
            ('执行信息', {
                'fields': ('executor', 'started_at', 'completed_at', 'expected_completion_date'),
                'classes': ('collapse',)
            }),
            ('成本信息', {
                'fields': ('estimated_cost', 'actual_cost'),
                'classes': ('collapse',)
            }),
            ('时间信息', {
                'fields': ('created_at', 'updated_at'),
                'classes': ('collapse',)
            }),
        )
        
        actions = ['approve_transfers', 'reject_transfers', 'start_execution']
        
        def status_colored(self, obj):
            colors = {
                'draft': '#6c757d',
                'pending': '#ffc107',
                'approved': '#007cba',
                'rejected': '#dc3545',
                'in_transit': '#fd7e14',
                'completed': '#28a745',
                'cancelled': '#6c757d'
            }
            color = colors.get(obj.status, '#6c757d')
            return format_html(
                '<span style="color: {}; font-weight: bold;">{}</span>',
                color,
                obj.get_status_display()
            )
        status_colored.short_description = '状态'
        
        def priority_colored(self, obj):
            colors = {
                'low': '#28a745',
                'medium': '#007cba',
                'high': '#ffc107',
                'urgent': '#dc3545'
            }
            color = colors.get(obj.priority, '#6c757d')
            return format_html(
                '<span style="color: {}; font-weight: bold;">{}</span>',
                color,
                obj.get_priority_display()
            )
        priority_colored.short_description = '优先级'
        
        def asset_count_info(self, obj):
            count = getattr(obj, 'asset_count', 0)
            return format_html(
                '<span style="color: #007cba; font-weight: bold;">{} 项</span>',
                count
            )
        asset_count_info.short_description = '资产数量'
        
        def approve_transfers(self, request, queryset):
            updated = 0
            for transfer in queryset.filter(status='pending'):
                if hasattr(transfer, 'approve') and transfer.can_approve(request.user):
                    transfer.approve(request.user, '批量审批通过')
                    updated += 1
            self.message_user(request, f'成功审批通过 {updated} 个调拨申请。')
        approve_transfers.short_description = '批量审批通过'
        
        def reject_transfers(self, request, queryset):
            updated = 0
            for transfer in queryset.filter(status='pending'):
                if hasattr(transfer, 'reject') and transfer.can_approve(request.user):
                    transfer.reject(request.user, '批量审批拒绝')
                    updated += 1
            self.message_user(request, f'成功拒绝 {updated} 个调拨申请。')
        reject_transfers.short_description = '批量审批拒绝'
        
        def start_execution(self, request, queryset):
            updated = 0
            for transfer in queryset.filter(status='approved'):
                if hasattr(transfer, 'start_execution') and transfer.can_execute(request.user):
                    transfer.start_execution(request.user)
                    updated += 1
            self.message_user(request, f'成功开始执行 {updated} 个调拨申请。')
        start_execution.short_description = '开始执行调拨'

except NameError:
    pass


# 工作流模块
try:
    @admin.register(WorkflowTemplate)
    class WorkflowTemplateAdmin(admin.ModelAdmin):
        list_display = ['name', 'template_type', 'is_active_status', 'instance_count', 'created_at']
        list_filter = ['template_type', 'is_active', DateRangeFilter]
        search_fields = ['name', 'description']
        readonly_fields = ['created_at', 'updated_at']
        
        fieldsets = (
            ('基本信息', {
                'fields': ('name', 'template_type', 'description', 'is_active')
            }),
            ('流程定义', {
                'fields': ('workflow_definition',),
                'classes': ('wide',)
            }),
            ('时间信息', {
                'fields': ('created_at', 'updated_at'),
                'classes': ('collapse',)
            }),
        )
        
        def is_active_status(self, obj):
            if obj.is_active:
                return format_html(
                    '<span style="color: #28a745; font-weight: bold;">启用</span>'
                )
            return format_html(
                '<span style="color: #dc3545; font-weight: bold;">禁用</span>'
            )
        is_active_status.short_description = '状态'
        
        def instance_count(self, obj):
            if hasattr(obj, 'workflowinstance_set'):
                count = obj.workflowinstance_set.count()
                return format_html(
                    '<span style="color: #007cba; font-weight: bold;">{} 个实例</span>',
                    count
                )
            return '0 个实例'
        instance_count.short_description = '实例数量'

except NameError:
    pass


# 软件管理模块
try:
    @admin.register(Software)
    class SoftwareAdmin(admin.ModelAdmin):
        list_display = ['name', 'vendor', 'category', 'license_count', 'installation_count', 'created_at']
        list_filter = ['category', 'vendor', DateRangeFilter]
        search_fields = ['name', 'vendor', 'description']
        readonly_fields = ['created_at', 'updated_at']
        
        def license_count(self, obj):
            count = obj.licenses.count()
            return format_html(
                '<span style="color: #007cba; font-weight: bold;">{}</span>',
                count
            )
        license_count.short_description = '许可证数量'
        
        def installation_count(self, obj):
            count = sum(license.installations.count() for license in obj.licenses.all())
            return format_html(
                '<span style="color: #28a745; font-weight: bold;">{}</span>',
                count
            )
        installation_count.short_description = '安装数量'
    
    
    @admin.register(SoftwareLicense)
    class SoftwareLicenseAdmin(admin.ModelAdmin):
        list_display = ['software', 'license_key_masked', 'seats', 'status_colored', 'validity_period', 'usage_info']
        list_filter = ['status', 'software', DateRangeFilter]
        search_fields = ['software__name', 'license_key']
        autocomplete_fields = ['software', 'supplier']
        readonly_fields = ['created_at', 'updated_at']
        
        fieldsets = (
            ('基本信息', {
                'fields': ('software', 'license_key', 'seats', 'status')
            }),
            ('有效期', {
                'fields': ('start_date', 'end_date'),
                'classes': ('wide',)
            }),
            ('供应商信息', {
                'fields': ('supplier', 'notes'),
                'classes': ('collapse',)
            }),
            ('时间信息', {
                'fields': ('created_at', 'updated_at'),
                'classes': ('collapse',)
            }),
        )
        
        def license_key_masked(self, obj):
            if obj.license_key:
                key = obj.license_key
                if len(key) > 8:
                    return f"{key[:4]}****{key[-4:]}"
                return key
            return '-'
        license_key_masked.short_description = '许可证密钥'
        
        def status_colored(self, obj):
            colors = {
                'active': '#28a745',
                'expired': '#dc3545',
                'revoked': '#6c757d'
            }
            color = colors.get(obj.status, '#007cba')
            return format_html(
                '<span style="color: {}; font-weight: bold;">{}</span>',
                color,
                obj.get_status_display()
            )
        status_colored.short_description = '状态'
        
        def validity_period(self, obj):
            if obj.start_date and obj.end_date:
                return f"{obj.start_date} 至 {obj.end_date}"
            elif obj.end_date:
                return f"截至 {obj.end_date}"
            return '永久'
        validity_period.short_description = '有效期'
        
        def usage_info(self, obj):
            used = obj.installations.filter(uninstalled_at__isnull=True).count()
            total = obj.seats
            if used > total:
                color = '#dc3545'
            elif used == total:
                color = '#ffc107'
            else:
                color = '#28a745'
            
            return format_html(
                '<span style="color: {}; font-weight: bold;">{}/{}</span>',
                color, used, total
            )
        usage_info.short_description = '使用情况'
    
    
    @admin.register(SoftwareInstallation)
    class SoftwareInstallationAdmin(admin.ModelAdmin):
        list_display = ['license', 'target_info', 'installed_at', 'installation_status', 'notes_truncated']
        list_filter = ['license__software', 'installed_at', DateRangeFilter]
        search_fields = ['license__software__name', 'asset__name', 'user__username', 'department__name']
        autocomplete_fields = ['license', 'asset', 'user', 'department']
        readonly_fields = ['installed_at']
        
        def target_info(self, obj):
            if obj.asset:
                return format_html(
                    '<span style="color: #007cba;">资产: {}</span>',
                    obj.asset.name
                )
            elif obj.user:
                return format_html(
                    '<span style="color: #28a745;">用户: {}</span>',
                    obj.user.username
                )
            elif obj.department:
                return format_html(
                    '<span style="color: #6f42c1;">部门: {}</span>',
                    obj.department.name
                )
            return '-'
        target_info.short_description = '安装目标'
        
        def installation_status(self, obj):
            if obj.uninstalled_at:
                return format_html(
                    '<span style="color: #6c757d; font-weight: bold;">已卸载</span>'
                )
            return format_html(
                '<span style="color: #28a745; font-weight: bold;">已安装</span>'
            )
        installation_status.short_description = '安装状态'
        
        def notes_truncated(self, obj):
            if obj.notes:
                return obj.notes[:30] + '...' if len(obj.notes) > 30 else obj.notes
            return '-'
        notes_truncated.short_description = '备注'

except NameError:
    pass


# 系统管理模块
try:
    @admin.register(SystemLog)
    class SystemLogAdmin(admin.ModelAdmin):
        list_display = ['level_colored', 'module', 'action', 'user', 'ip_address', 'created_at']
        list_filter = ['level', 'module', DateRangeFilter]
        search_fields = ['action', 'message', 'user__username', 'ip_address']
        readonly_fields = ['created_at']
        date_hierarchy = 'created_at'
        
        def level_colored(self, obj):
            colors = {
                'DEBUG': '#6c757d',
                'INFO': '#007cba',
                'WARNING': '#ffc107',
                'ERROR': '#dc3545',
                'CRITICAL': '#721c24'
            }
            color = colors.get(obj.level, '#6c757d')
            return format_html(
                '<span style="color: {}; font-weight: bold;">{}</span>',
                color,
                obj.get_level_display()
            )
        level_colored.short_description = '级别'

except NameError:
    pass